package com.swiftride.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swiftride.constants.Constants;
import com.swiftride.constants.GlobalExceptionCode;
import com.swiftride.exception.GlobalException;
import com.swiftride.feign.UaaFeign;
import com.swiftride.mapper.CustomerMapper;
import com.swiftride.pojo.domain.Customer;
import com.swiftride.pojo.domain.CustomerSummary;
import com.swiftride.pojo.domain.CustomerWallet;
import com.swiftride.pojo.param.RegisterParam;
import com.swiftride.service.ICustomerService;
import com.swiftride.service.ICustomerSummaryService;
import com.swiftride.service.ICustomerWalletService;
import com.swiftride.template.AppWeChatTemplate;
import com.swiftride.utils.AssertUtil;
import com.swiftride.utils.BitStatesUtil;
import com.swiftride.utils.SMSUtils;
import com.swiftride.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author wy
 * @since 2024-07-31
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {
    @Autowired
    private ICustomerWalletService walletService;

    @Autowired
    private ICustomerSummaryService summaryService;

    @Autowired
    private AppWeChatTemplate appWeChatTemplate;

    @Autowired
    private UaaFeign uaaFeign;

    @Override
    @Transactional
    public void register(String openidCode) {
        //1.参数效验 使用jsr303完成
        //2.1获取openid
        String openid = appWeChatTemplate.getOpenid(openidCode);
        //2.2判断乘客是否已经注册过
        Customer customer = super.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getOpenId, openid));
        AssertUtil.isNull(customer, GlobalExceptionCode.PARAM_PHONE_EXIST);
        //3.业务实现
        saveInfo(openid, Constants.DEFAULT_PHONE);

    }

    @Override
    @Transactional
    public void register(String openidCode, String phoneCode) {
        //1.参数效验 使用jsr303完成
        //2.业务验证
        //2.1获取openid
        String openid = appWeChatTemplate.getOpenid(openidCode);
        //2.2判断司机是否已经注册过
        Customer customer = super.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getOpenId, openid));
        AssertUtil.isNull(customer, GlobalExceptionCode.PARAM_PHONE_EXIST);
        //2.2获取电话号码
        String phoneNum = appWeChatTemplate.getPhoneNum(phoneCode);
        //3.业务实现
        saveInfo(openid, phoneNum);
    }

    /**
     * 保存信息
     *
     * @param openid   openid
     * @param phoneNum 电话号码
     */
    private void saveInfo(String openid, String phoneNum) {
        //3.业务实现
        //3.1初始化密码
        String password = Constants.DEFAULT_PASSWORD;
        //BCrypt加密
        String pwHash = BCrypt.hashpw(password, BCrypt.gensalt());
        //3.2保存乘客信息
        Customer customer = new Customer();
        customer.init();
        customer.setOpenId(openid);
        customer.setPhone(phoneNum);
        customer.setBitState(BitStatesUtil.addState(customer.getBitState(), BitStatesUtil.OP_PHONE));
        save(customer);
        //3.3保存乘客关联信息
        initCustomerAssociation(customer.getId(), pwHash);
        //3.2保存登录表
        saveLogin(customer, pwHash);
    }

    /**
     * 保存customer表的关联表
     *
     * @param id 乘客的id
     */
    private void initCustomerAssociation(Long id, String password) {
        //初始化关联表summary
        CustomerSummary customerSummary = new CustomerSummary();
        customerSummary.init();
        customerSummary.setId(id);
        summaryService.save(customerSummary);

        //初始化关联表wallet
        CustomerWallet customerWallet = new CustomerWallet();
        customerWallet.init();
        customerWallet.setId(id);
        customerWallet.setPassword(password);
        walletService.save(customerWallet);
    }

    /**
     * 保存customer对应的登录表
     *
     * @param customer 乘客的信息
     */
    private void saveLogin(Customer customer, String password) {
        RegisterParam registerParam = new RegisterParam();
        registerParam.init();
        registerParam.setUsername(customer.getPhone());
        registerParam.setPassword(password);
        registerParam.setType(Constants.Login.TYPE_CUSTOMER);
        registerParam.setOpenId(customer.getOpenId());
        registerParam.setPhone(customer.getPhone());

        uaaFeign.register(registerParam);
    }

    /**
     * 根据手机号发送短信
     *
     * @param phoneNum 手机号
     */
    private static void sendTextMessage(String phoneNum) {
        //生成 随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //调用阿里云提供的短信服务API 完成发送短信
        //参数分别是signName, templateCode, phoneNumbers, param
        try {
            SMSUtils.sendMessage("阿里云短信测试", phoneNum, code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(GlobalExceptionCode.SERVICE_ERROR);
        }
    }
}
